﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace hyjiacan.util.web.wp
{
    public static class DBUtil
    {
        private static string connectionString = "server={0}; user id={1}; password={2}; database={3};Allow Zero Datetime=True;";

        static MySqlConnection con;

        static string prefix
        {
            get
            {
                return Settings.Get(Settings.Items.Prefix);
            }
        }

        /// <summary>
        /// 连接到数据库
        /// </summary>
        /// <param name="server"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="database"></param>
        public static MySqlConnection Connect(string server, string username, string password, string database)
        {
            con = new MySqlConnection(string.Format(connectionString, server, username, password, database));
            con.Open();
            return con;
        }

        public static MySqlConnection Connect()
        {
            return Connect(Settings.Get(Settings.Items.Server), Settings.Get(Settings.Items.Username), Settings.Get(Settings.Items.Password), Settings.Get(Settings.Items.Database));
        }

        public static void Execute(string sql)
        {
            MySqlConnection conn = Connect();
            try
            {
                MySqlCommand cmd = con.CreateCommand();
                cmd.CommandText = sql.Replace("{prefix}", prefix);
                cmd.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }

        public static DataTable Select(string sql)
        {
            MySqlConnection conn = Connect();
            DataTable data = new DataTable();
            try
            {
                MySqlDataAdapter da = new MySqlDataAdapter(sql.Replace("{prefix}", prefix), conn);

                da.Fill(data);
            }
            finally
            {
                con.Close();
            }
            return data;
        }

        public static string GetCellValue(DataRow row, int index)
        {
            object cell = row[index];
            if (cell.GetType() == typeof(DBNull))
            {
                return null;
            }
            return cell.ToString();
        }

        public static string GetCellValue(DataRow row, string colName)
        {
            object cell = row[colName];
            if (cell.GetType() == typeof(DBNull))
            {
                return null;
            }
            return cell.ToString();
        }
    }
}
